from datetime import datetime, timedelta
from typing import Optional
from itsdangerous import URLSafeTimedSerializer
import bcrypt
from app.core.config import settings
from jose import JWTError, jwt

# 创建序列化器
serializer = URLSafeTimedSerializer(settings.SECRET_KEY)

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """创建访问令牌"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)  # 默认过期时间为15分钟
    to_encode.update({"exp": expire})
    return serializer.dumps(to_encode)

def verify_token(token: str, max_age: int = 3600) -> Optional[dict]:
    """验证令牌"""
    try:
        return serializer.loads(token, max_age=max_age)
    except:
        return None

def get_password_hash(password: str) -> str:
    """获取密码哈希"""
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码"""
    return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())

def decode_jwt(token: str):
    """解码 JWT 并返回用户信息"""
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        return payload  # payload 中包含 "sub" 和其他信息
    except JWTError:
        return None 